<template>
  <div>
    <div class="area-header" style="margin-top: 15px;">
      <span class="area-header-title">{{ fileTitle ? $t(fileTitle) : $t('附件信息') }}</span>
      <span v-show="false">{{ lists }}</span>
    </div>
    <el-table ref="table" v-loading="loading" tooltip-effect="darkTable" :data.sync="lists" border :row-key="getRowKeys" class="nowrapTable formTable printArea" @cell-mouse-enter.once="rowDrop" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="40" :selectable="checkSelectable" />
      <el-table-column align="center" prop="directoryName" :show-overflow-tooltip="true" width="140px">
        <template slot="header" slot-scope="{}">
          <span>{{ $t('文件分类') }}</span>
        </template>
        <template slot-scope="scope">
          <span style="display: none">{{ scope.row }}</span>
          <div class="handle directory-handle">
            <i class="el-icon-rank link-type" :title="$t('拖拽排序')" />
            <span :class="{'isDirectory': (requiredIsAllTrue ? scope.row.checkRequired === 'true' : false)}">{{ $t(scope.row.directoryName) }}</span>
            <span style="display: none">{{ requiredIsAllTrue }} {{ scope.row.checkRequired }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column :label="$t('附件名称')" align="center" prop="name" min-width="150" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <el-form-item :prop="'name'" style="overflow: hidden;text-overflow: ellipsis;white-space: nowrap;" :rules="[{ required: true, validator: checkNameIsNull, index: scope.$index, values: scope.row.name, trigger: ['blur', 'change'] }]">
            <a v-if="scope.row.name !== '' || scope.row.name != null" class="link_a" @click="onlinePreview(scope.row, 'view')">
              <div :style="{ color: (mark[scope.$index] !== undefined && mark[scope.$index].name === scope.row.name && mark[scope.$index].nameMark) ? 'red' : '#1890ff' }">
                <div style="text-align: left;overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">{{ scope.row.name }}</div>
              </div>
            </a>
            <upload
              v-if="scope.row.name === undefined || scope.row.name === '' || scope.row.name === null"
              :data-type="dataType"
              :file-id="scope.row.id"
              class="upload-single"
              @appendData="getSingleData($event, scope.$index)"
            />
          </el-form-item>
        </template>
      </el-table-column>
      <!-- 组态插件 -->
      <template v-if="slotInputBoxDataArr && slotInputBoxDataArr.length > 0">
        <el-table-column v-for="(field, index) in slotInputBoxDataArr" :key="field + index" :label="field.label" :prop="field.model" :min-width="field.minWidth" :max-width="field.maxWidth" align="center">
          <template slot="header" slot-scope="{}">
            <span>{{ field.label }}</span>
            <span v-show="isEmpty(field.required) ? false : field.required" style="color: red">*</span>
          </template>
          <template slot-scope="scope">
            <el-form-item
              :prop="fileListName + '.' + scope.$index + '.slotData[' + index + '][' + field.model + ']'"
              :rules="[{ required: isEmpty(field.required) ? false : field.required, validator: checkAndSetValue, trigger: ['blur', 'change'] }]"
            >
              <indexSlot
                v-model="scope.row.slotData[index].value"
                :field="scope.row.slotData[index]"
                @changeSelect="changeSelect($event, scope.$index, field.model, scope.row.slotData)"
                @changeSlotNumber="changeSlotNumber($event, scope.$index, field.model, scope.row.slotData)"
                @changeSlotInput="changeSlotInput($event, scope.$index, field.model, scope.row.slotData)"
              />
            </el-form-item>
          </template>
        </el-table-column>
      </template>
      <el-table-column v-if="showType === 'normal'" :label="$t('备注')" align="center">
        <template slot-scope="scope">
          <el-input v-model="scope.row.remark" class="noPrintTextarea" type="textarea" maxlength="2000" :autosize="{ minRows: 1, maxRows: 10}" />
        </template>
      </el-table-column>
      <el-table-column v-if="showType === 'normal' && slotInputBoxDataArr.length <= 0" :label="$t('上传人')" align="center" prop="updateBy.nickName" show-overflow-tooltip width="100px">
        <template slot-scope="scope">
          <span>{{ scope.row.name ? scope.row.updateBy.nickName : '' }}</span>
        </template>
      </el-table-column>
      <el-table-column v-if="showType === 'normal' && slotInputBoxDataArr.length <= 0" :label="$t('上传时间')" align="center" prop="createTime" show-overflow-tooltip width="150px">
        <template slot-scope="scope">
          <span>{{ scope.row.name ? scope.row.createTime : '' }}</span>
        </template>
      </el-table-column>
      <!--      <el-table-column v-if="!officeSwitchStatus" :label="$t('操作')" align="center" class-name="small-padding fixed-width handleCol" width="90px">-->
      <!--        <template slot-scope="scope">-->
      <!--          <el-button v-if="configDownloadEnabled" :disabled="scope.row.id === '' || scope.row.id === undefined || scope.row.id === null" size="small" type="text" icon="el-icon-download" @click="download(scope.row)" />-->
      <!--          <el-button v-if="btnShow === true" size="small" type="text" icon="el-icon-delete" @click="delAdjunct(scope.$index, scope.row)" />-->
      <!--          <el-button-->
      <!--            v-if="scope.row.discussId !== null && scope.row.discussId !== '' && scope.row.discussId !== undefined"-->
      <!--            size="small"-->
      <!--            type="text"-->
      <!--            icon="el-icon-data-analysis"-->
      <!--            @click="discussionNotice(scope.row)"-->
      <!--          >{{ $t('讨论') }}</el-button>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <el-table-column v-if="isSetting" fixed="right" :label="$t('操作')" align="center" class-name="small-padding fixed-width handleCol" width="90px">
        <template slot-scope="scope">
          <el-dropdown trigger="click">
            <span class="el-dropdown-link">
              <i class="el-icon-more" />
            </span>
            <el-dropdown-menu slot="dropdown">
              <!-- 编辑 -->
              <el-dropdown-item>
                <el-button
                  v-if="editBtnShow(scope)"
                  v-hasPermi="btnHasPermi"
                  :disabled="isDisabled(scope.row)"
                  size="small"
                  type="text"
                  icon="el-icon-edit"
                  @click="onlinePreview(scope.row, 'review')"
                >{{ $t('编辑') }}</el-button>
              </el-dropdown-item>
              <!-- 下载-->
              <el-dropdown-item>
                <el-button
                  v-if="downloadBtnShow(scope)"
                  :disabled="(scope.row.id === '' || scope.row.id === undefined || scope.row.id === null) && (scope.row.fileSource === '' || scope.row.fileSource === undefined || scope.row.fileSource === null)"
                  size="small"
                  type="text"
                  icon="el-icon-download"
                  @click="download(scope.row)"
                >{{ $t('下载') }}</el-button>
              </el-dropdown-item>
              <!-- 检查-->
              <el-dropdown-item>
                <el-button
                  v-if="filePoteUserFlag && typeContainsAdjust(scope.row)"
                  size="small"
                  type="text"
                  icon="el-icon-document-checked"
                  @click="errorCorrection(scope.row)"
                >{{ $t('检查') }}</el-button>
              </el-dropdown-item>
              <!-- 删除 LOGO区分-->
              <el-dropdown-item>
                <el-button
                  v-if="deleteBtnShow(scope)"
                  v-hasPermi="btnHasPermi"
                  size="small"
                  type="text"
                  icon="el-icon-delete"
                  :disabled="scope.row.deleteStatus"
                  @click="delAdjunct(scope.$index, scope.row)"
                >{{ $t('删除') }}</el-button>
                <el-button
                  v-if="btnShow && !(scope.row.dataId && !scope.row.deleteStatus)"
                  v-hasPermi="btnHasPermi"
                  size="small"
                  type="text"
                  icon="el-icon-document-delete"
                  @click="delSplit(scope.$index, scope.row, scope.row.deleteStatus)"
                >{{ $t('删除') }}</el-button>
              </el-dropdown-item>
              <!-- 回显 -->
              <span>
                <el-tooltip placement="left">
                  <div slot="content">
                    {{ $t('当前文件已从文档库隐藏, 点击该按钮可还原在文档库中的默认显示状态') }}
                  </div>
                  <el-dropdown-item
                    v-if="scope.row.hideStatus === 'N'"
                    @click.native="restoreEcho(scope.row)"
                  >
                    <el-button
                      v-if="(scope.row.id !== '' && scope.row.id !== undefined && scope.row.id !== null)"
                      size="small"
                      type="text"
                      icon="el-icon-refresh"
                    >{{ $t('还原') }}</el-button>
                  </el-dropdown-item>
                </el-tooltip>
              </span>
              <!-- 版本 -->
              <el-dropdown-item>
                <el-button
                  v-if="versionBtnShow(scope)"
                  size="small"
                  type="text"
                  icon="el-icon-time"
                  @click="fileOrDirRecord(scope.row)"
                >{{ $t('版本') }}</el-button>
              </el-dropdown-item>
              <!-- 讨论 scope.row.discussId -->
              <el-dropdown-item>
                <el-button
                  v-if="versionBtnShow(scope)"
                  size="small"
                  type="text"
                  icon="el-icon-data-analysis"
                  @click="discussionNotice(scope.row)"
                >{{ $t('讨论') }}</el-button>
              </el-dropdown-item>
              <!-- 重新上传 -->
              <el-dropdown-item v-if="reloadBtnShow(scope)" v-hasPermi="btnHasPermi">
                <div>
                  <reUpload
                    v-if="btnShow === true"
                    ref="reUploadRef"
                    :get-file-object="scope.row"
                    :data-type="dataType"
                    @okPostUploadHook="okPostUploadHook"
                    @replaceNewFile="replaceNewFile"
                    @replaceNewFileNotOldId="replaceNewFileNotOldId"
                  />
                </div>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    <div class="tol" :style="{ display: ((batchDownloadChoice.length > 0) ? 'block !important' : (btnShow !== false ? '' : 'none !important')) }">
      <el-button v-if="btnShow !== false" v-hasPermi="btnHasPermi" type="primary" icon="el-icon-plus" size="mini" @click="uploader">{{ $t('上传') }}</el-button>
      <el-tooltip v-model="batchDownloadSwitch" :manual="true" :content="$t('请先选择有效附件, 再进行批量下载')" placement="right">
        <el-button
          v-if="configDownloadEnabled && batchDownloadChoice.length > 0"
          :loading="batchDownloadLoading"
          type="primary"
          style="pointer-events: unset !important;cursor: pointer;"
          icon="el-icon-download"
          size="mini"
          @click="batchDownload"
        >{{ $t('下载') + downloadCount }}</el-button>
      </el-tooltip>
    </div>

    <!-- 上传附件 -->
    <el-dialog v-if="uploaderOpen && isSetting" v-el-drag-dialog :title="$t('上传附件')" :visible.sync="uploaderOpen" :destroy-on-close="true" :close-on-click-modal="false" width="50%" append-to-body :before-close="handleDialogClose">
      <Upload
        ref="upload"
        :file-id="fileId"
        :data-type="dataType"
        :business-id="businessId"
        :show-type="showType"
        :business-type="businessType"
        :main-body-vue-show="mainBodyVueShow"
        :select-business-data="selectBusinessData"
        :specify-file-suffix="specifyFileSuffix"
        :specify-file-size="specifyFileSize"
        :hidden-type-flag="hiddenTypeFlag"
        @appendData="getData($event)"
      />
    </el-dialog>

    <!--操作版本页面-->
    <el-dialog :title="title" :visible.sync="historicalFileLoading" :close-on-click-modal="false" width="80%" :destroy-on-close="true" append-to-body>
      <historicalFile ref="historicalFile" @refreshFileInfo="refreshFileInfo" />
    </el-dialog>
    <!-- 检测 -->
    <el-dialog :title="$t('文档检查')" :visible.sync="examineOpen" width="300px" :close-on-click-modal="false" :lock-scroll="false" append-to-body>
      <examine ref="examine" />
    </el-dialog>
    <!-- 讨论通知 -->
    <el-dialog :title="$t('评论')" :visible.sync="commentsOpen" :close-on-click-modal="false" :lock-scroll="false" custom-class="commentsDigOnly" append-to-body>
      <comments ref="comments" />
    </el-dialog>

    <!-- 预览附件 -->
    <OnlinePreview ref="OnlinePreview" :preview-tit="previewTit" />
  </div>
</template>
<script>
import Sortable from 'sortablejs'
import comments from '@/views/file/document/comments.vue'
import reUpload from '@/components/File/FileTable/subassembly/reUpload.vue'
import historicalFile from '@/views/file/document/library/historicalFile.vue'
import upload from '@/components/File/Upload/single.vue'
import indexSlot from '@/components/File/FileTable/fileTableSlot.vue'
import { deleteFileBase, restoreEchoFile } from '@/api/file/filefolder/folder.js'
import { getSysVarValue } from '@/api/system/config'
import { downLoadFileOpen, downLoadZip } from '@/utils/zipdownload'
import { getFileConfigByCode } from '@/api/file/fileConfig/fileConfig'
import { getCheckRequired, getFileById } from '@/api/file/fileBase'
import examine from '@/views/file/examine/examine'
export default {
  components: {
    indexSlot,
    upload,
    historicalFile,
    reUpload,
    examine,
    comments
  },
  props: {
    hiddenTypeFlag: {
      type: Boolean,
      default: () => false
    },
    hasPermi: {
      type: String,
      default: undefined
    },
    list: {
      type: Array,
      default: () => []
    },
    dataType: {
      type: String,
      required: true,
      default: () => ''
    },
    // 是否展示选择项目, 基金...的下拉
    mainBodyVueShow: {
      type: Boolean,
      default: () => true
    },
    businessId: {
      type: String,
      default: () => ''
    },
    // 当businessType有值时. businessId失效. 将不会更具这个Id列出目录
    businessType: {
      type: String,
      default: () => ''
    },
    btnShow: {
      type: Boolean,
      default: true
    },
    // 展示类型
    showType: {
      type: String,
      default: 'normal'
    },
    // 如果选择了特定的业务类型，是否需要选择业务数据
    selectBusinessData: {
      type: Boolean,
      default: true
    },
    // 突显某个字段
    mark: {
      type: Array,
      default: () => []
    },
    fileTitle: {
      type: String,
      default: () => ''
    },
    /** 默认表单需要上传的文件类型, 去fileConfig.vue配置 start */
    // 是否校验附件必填
    fileConfigRequired: {
      type: Boolean,
      default: () => true
    },
    // 文件校验配置类型
    fileConfigType: {
      type: String,
      default: () => undefined
    },
    /** 默认表单需要上传的文件类型, 去fileConfig.vue配置 start */
    // 指定文件后缀上传
    specifyFileSuffix: {
      type: Array,
      default: undefined
    },
    // 指定文件大小(单位MB)
    specifyFileSize: {
      type: Number,
      default: undefined
    },
    isSetting: {
      type: Boolean,
      default: () => true
    },
    // 插槽属性: 展示哪种类型的输入框类型
    slotInputBoxData: {
      type: Array,
      default: () => []
    },
    // 后台传递附件的名字, 这里必须填对. 否则不校验表单
    fileListName: {
      type: String,
      default: () => 'fileList'
    }
  },
  data() {
    return {
      title: '',
      previewTit: '',
      uploaderOpen: false,
      commentsOpen: false,
      examineOpen: false,
      filePoteUserFlag: false,
      previewType: '',
      name: '',
      lists: [],
      initFileIndex: '',
      fileId: '',
      loading: false,
      // 编辑按钮
      officeSwitchStatus: false,
      historicalFileLoading: false,
      // 文档检验必填文件
      fileConfigArray: [],
      // 校验需要上传的目录类型
      checkFolderType: undefined,
      // 全局下载开关
      configDownloadEnabled: true,
      btnHasPermi: this.hasPermi ? [this.hasPermi + ':edit'] : [],
      slotInputBoxDataArr: [],
      // 批量下载选择数组
      batchDownloadChoice: [],
      // 批量下载按钮必选校验开关
      batchDownloadSwitch: false,
      // 批量下载按钮加载状态
      batchDownloadLoading: false,
      downloadCount: ''
    }
  },
  computed: {
    // 是否显示必传附件表示
    requiredIsAllTrue: function() {
      console.log('判断必填标识')
      var flag = false
      this.lists.forEach((item, index) => {
        var value = item.name
        if ((value === undefined || value === null || value === '') && this.fileConfigRequired && window.localStorage.getItem('fileConfigRequired') === 'true') {
          if (this.lists[index].checkRequired === 'true') {
            flag = true
          }
        }
      })
      return flag
    }
  },
  watch: {
    'list': {
      handler(val) {
        this.lists = val
        this.checkFileConfig()
        if (this.lists !== null && this.lists !== undefined) {
          for (var i = 0; i < this.lists.length; i++) {
            if (this.lists[i].dataType === null) {
              this.lists[i].dataType = this.dataType
            }
          }
        }
        this.$forceUpdate()
      },
      deep: true,
      immediate: true
    },
    'lists': {
      handler(val) {
        if (val) {
          val && val.forEach(item => {
            item.dataType = this.dataType
            // 插槽中的数据
            if (this.isEmpty(item.slotData)) {
              item.slotData = this.slotInputBoxData
            }
          })
          // 自动添加排序序号.
          this.autoFileListSort()
        }
      }
    },
    slotInputBoxData: {
      handler(val) {
        if (!this.isEmpty(val)) {
          this.slotInputBoxDataArr = val
        } else {
          this.slotInputBoxDataArr = []
        }
        this.$forceUpdate()
      },
      deep: true,
      immediate: true
    },
    'fileConfigType': {
      handler(val) {
        if (val === undefined || val === '' || val === null) {
          this.checkFolderType = 'file_config_' + this.dataType
        } else {
          this.checkFolderType = val
        }
      },
      deep: true,
      immediate: true
    }
  },
  mounted() {
    this.name = this.$store.getters.name
    this.getOfficeSwitch()
    // 初始化文档检验.判断是否存在必填文件
    this.initFileConfig()
  },
  created() {
    // 全局下载开关
    this.getConfigKeyToDownload('enable_download').then(response => {
      this.configDownloadEnabled = (response.msg === 'true')
    })
    console.log('使用开关', this.$store.state.app.filePoteUser)
    if (this.$store.state.app.filePoteUser === 'Y') {
      this.filePoteUserFlag = true
    } else {
      this.filePoteUserFlag = false
    }
    console.log('使用开关赋值后的结果值', this.filePoteUserFlag)

    window.localStorage.setItem('fileConfigRequired', true)
  },
  updated() {
    // 获取该表单中附件的必填目录, 一般修改时或流程审批页面中提交时进行逻辑补充
    if (this.$parent.$parent.form && this.$parent.$parent.form.id && !this.firstExceStatus && this.isEmpty(this.fileConfigArray)) {
      this.firstExceStatus = true
      getCheckRequired(this.dataType, this.$parent.$parent.form.id).then(response => {
        response.data.forEach(item => {
          item.deleteStatus = item.checkRequired === 'true'
          this.fileConfigArray.push(item)
        })

        var folderDirectoryIds = []
        this.fileConfigArray.forEach(item => {
          folderDirectoryIds.push(item.directoryId)
        })
        this.list.forEach(item => {
          const object = this.fileConfigArray.find(obj => obj.directoryId === item.directoryId)
          if (object) {
            item.checkRequired = object.checkRequired
          } else {
            item.checkRequired = 'false'
          }
        })
        // 配置的目录不能删除
        if (this.lists) {
          this.lists.forEach(item => {
            if (folderDirectoryIds.includes(item.directoryId)) {
              item.deleteStatus = true
            }
          })
        }
        // 强制刷新 强制渲染
        this.$forceUpdate()
      })
    }
  },
  methods: {
    /**        文档沉淀必填校验 start      **/
    checkNameIsNull(rule, value, callback) {
      value = rule.values
      if ((value === undefined || value === null || value === '') && this.fileConfigRequired && window.localStorage.getItem('fileConfigRequired') === 'true') {
        if (this.lists[rule.index].checkRequired === 'true') {
          callback(new Error(this.$t('必填信息')))
        } else {
          callback()
        }
      } else {
        callback()
      }
    },
    initFileConfig() {
      if (this.checkFolderType !== undefined && this.checkFolderType !== null && this.checkFolderType !== '') {
        this.loading = true
        getFileConfigByCode(this.checkFolderType, 'WDJJ').then(response => {
          if (response.data !== null && response.data.documentTypeArray !== null) {
            response.data.documentTypeArray.forEach(item => {
              const row = {
                directoryName: item.name,
                directoryId: item.id,
                name: '',
                checkRequired: 'true',
                deleteStatus: true
              }
              this.fileConfigArray.push(row)
            })
          }
          if (response.data !== null && response.data.documentNonTypeArray !== null) {
            response.data.documentNonTypeArray.forEach(item => {
              const row = {
                directoryName: item.name,
                directoryId: item.id,
                name: '',
                checkRequired: 'false',
                deleteStatus: false
              }
              this.fileConfigArray.push(row)
            })
          }
          this.loading = false
          this.checkFileConfig()
        })
      }
    },
    // 文档审核目前支持doc、docx、pdf格式文件审核，最大支持50w字，1GB大小的文件
    typeContainsAdjust(row) {
      // console.log('校验文档格式', row)
      var name = row.name
      if (name !== null && name !== undefined && name !== '') {
        var suffix = row.name.substring(name.lastIndexOf('.') + 1)
        const availableSuffixes = '.doc.docx.pdf'
        if (availableSuffixes.includes(suffix)) {
          return true
        }
      }
      return false
    },
    // 文档纠错（文档审核）
    errorCorrection(row) {
      this.examineOpen = true
      this.$nextTick(() => {
        this.$refs.examine.init(row)
      })
    },
    // 校验表单中是否存在这些必填的文件
    checkFileConfig() {
      var folderDirectoryIds = []
      this.fileConfigArray.forEach(item => {
        folderDirectoryIds.push(item.directoryId)
      })
      this.fileConfigArray.forEach(item => {
        const object = this.list.find(obj => obj.directoryId === item.directoryId)
        if (!object) {
          this.list.push({
            directoryName: item.directoryName,
            directoryId: item.directoryId,
            name: '',
            checkRequired: item.checkRequired,
            deleteStatus: true
          })
        } else {
          console.error(item)
          object.checkRequired = item.checkRequired
        }
      })
      // 配置的目录不能删除
      if (this.lists) {
        this.lists.forEach(item => {
          if (folderDirectoryIds.includes(item.directoryId)) {
            item.deleteStatus = true
          }
        })
      }
      // 强制刷新 强制渲染
      this.$forceUpdate()
    },
    /**        文档沉淀必填校验 end      **/
    // 单文件上传
    getSingleData(data, index) {
      data.fileId = data.fileId || data.id
      data.fileName = data.fileName || data.name
      if (data.fileId !== '') {
        this.$set(this.lists[index], 'name', data.fileName)
        this.$set(this.lists[index], 'id', data.fileId)
        this.$set(this.lists[index], 'createTime', this.getFormatDate())
        // this.$set(this.lists[index], 'createTime', this.getFormatDate())

        this.$set(this.lists[index], 'updateBy', { 'nickName': this.name })
        this.$nextTick(() => {
           this.$emit('update:list', this.lists)
        })
      }
      this.loading = false
    },
    /**
    * 点击 X 关闭对话框的回调
    **/
    handleDialogClose() {
       this.$set(this.$refs.upload.$refs.uploader, 'fileList', [])
       this.$set(this.$refs.upload.$refs.uploader.uploader, 'fileList', [])
       this.uploaderOpen = false
    },
    // 添加附件
    uploader(index, id) {
      this.fileId = id
      if (this.$parent.$parent.uploadBeforeTable !== undefined) {
        this.$emit('uploadBeforeTable', () => {
          this.uploaderOpen = true
          this.$nextTick(() => {
            this.$refs.upload.init()
          })
        })
      } else {
        this.uploaderOpen = true
        this.$nextTick(() => {
          this.$refs.upload.init()
        })
      }
    },
    getFormatDate() {
      var date = new Date()
      var month = date.getMonth() + 1
      var strDate = date.getDate()
      var h = date.getHours()
      var m = date.getMinutes()
      var s = date.getSeconds()
      if (month >= 1 && month <= 9) {
          month = '0' + month
      }
      if (strDate >= 0 && strDate <= 9) {
          strDate = '0' + strDate
      }
      var currentDate = date.getFullYear() + '-' + month + '-' + strDate + ' ' + h + ':' + m + ':' + s
      return currentDate
    },
    // 获取附件列表
    getData(row) {
      row.fileList.forEach((item) => {
        this.$set(item, 'directoryId', item.directoryId)
        this.$set(item, 'directoryName', item.directoryName)
        this.$set(item, 'remark', row.form.remark)
        this.$set(item, 'createTime', this.getFormatDate())
        this.$set(item, 'fileSource', item.fileSource)
        this.$set(item, 'updateBy', { 'nickName': this.name })
        if (!this.isEmpty(this.slotInputBoxDataArr)) {
          this.$set(item, 'slotData', JSON.parse(JSON.stringify(this.slotInputBoxDataArr)))
        }
        if (!(this.lists instanceof Array)) {
          this.$set(this, 'lists', [])
        }
        this.$nextTick(() => {
          this.lists.push(item)
          this.$emit('update:list', this.lists)
          this.$emit('handleChange', this.lists)
        })
      })
    },
    // 预览附件
    onlinePreview(row, type) {
      type === 'review' ? this.previewType = 'review' : this.previewType = 'view'
      var fileId = ((row.id === undefined || row.id === null || row.id === '') ? row.fileSource : row.id)
      this.$refs.OnlinePreview.onlinePreviewFile(fileId, type)
    },
    // 删除附件
    delAdjunct(index, row) {
      const id = row.id
      const that = this
      if (id !== undefined && id !== '' && id != null) {
        this.$confirm(this.$t('是否确认删除?'), this.$t('提示'), {
          confirmButtonText: this.$t('确定'),
          cancelButtonText: this.$t('取消'),
          type: 'warning'
        }).then(() => {
          this.loading = true
          this.lists.splice(index, 1)
          this.$emit('handleChange', this.lists)
          deleteFileBase(id).then(response => {
            if (response.code === 200) {
              this.msgSuccess(this.$t('删除成功'))
              // 删除某个文件后执行操作
              this.$emit('deleteSingleFile', row.id)
              this.loading = false
            } else {
              this.msgError(this.$t('删除异常'))
              this.loading = false
            }
          })
        }).catch(() => {
          that.loading = false
        })
      } else {
        this.lists.splice(index, 1)
        this.$emit('handleChange', this.lists)
      }
    },
    // 从列表删除
    delSplit(index, row, deleteStatus) {
      var temp = []
      if (this.lists && this.lists[index] && deleteStatus) {
        const dirId = this.lists[index].directoryId
        const object = this.fileConfigArray.find(obj => obj.directoryId === dirId)
        if (object) {
          this.lists.forEach(item => {
            if (dirId === item.directoryId) {
              temp.push(item.directoryId)
            }
          })
          if (temp.length <= 1) {
            console.log(this.lists[index])
            this.msgWarning(this.$t('该文件不可删除, 已为您清空数据, 请重新上传新文件!'))
            this.lists[index].createTime = undefined
            this.lists[index].updateBy = undefined
            this.lists[index].name = undefined
          } else {
            this.delAdjunct(index, row)
          }
        } else {
          this.lists.splice(index, 1)
        }
      } else {
        if (row.tempSource !== undefined && row.tempSource === 'library') {
          this.lists.splice(index, 1)
        } else {
          this.delAdjunct(index, row)
        }
      }
    },
    /**
     * 回显重新再文档库中显示
     */
    restoreEcho(row) {
      if (row && row.id) {
        const id = row.id
        restoreEchoFile({ fileId: id }).then(response => {
          if (response.data && response.data > 0) {
            row.hideStatus = undefined
            this.msgSuccess(this.$t(response.msg))
          }
        })
      }
    },
    // 下载
    download(row) {
      const fileId = (!this.isEmpty(row.id) && row.id !== '') ? row.id : row.fileSource
      console.log(row, fileId)
      downLoadFileOpen(fileId)
    },
    // 批量下载
    batchDownload() {
      if (this.isEmpty(this.batchDownloadChoice)) {
        this.batchDownloadSwitch = true
        setTimeout(() => {
          this.batchDownloadSwitch = false
        }, 2000)
      } else {
        console.log('批量下载', this.batchDownloadChoice)
        var fileIds = []
        this.batchDownloadChoice.forEach(item => {
          var fileId = item.id || item.fileId || item.fileSource
          fileIds.push(fileId)
        })
        downLoadZip('/file/fileBase/common/downloadZip?fileId=' + fileIds, this)
      }
    },
    downloadProgress(num) {
      this.downloadCount = num + '%'
    },
    downloadOpenLoading() {
      this.batchDownloadLoading = true
    },
    downloadCloseLoading() {
      this.downloadCount = ''
      this.batchDownloadLoading = false
    },
    // 多选
    handleSelectionChange(selection) {
      this.batchDownloadChoice = []
      selection.forEach(item => {
        if (!this.isEmpty(item.id) || !this.isEmpty(item.fileId) || !this.isEmpty(item.fileSource)) {
          this.batchDownloadChoice.push(item)
        }
      })
    },
    // 判断哪些行可以选择批量下载
    checkSelectable(row) {
      if (!this.isEmpty(row.id) || !this.isEmpty(row.fileId) || !this.isEmpty(row.fileSource)) {
        // 可选
        return 1
      } else {
        // 不可选
        return 0
      }
    },
    // 查看操作版本
    fileOrDirRecord(row) {
      this.historicalFileLoading = true
      this.title = this.$t('版本文件')
      this.$nextTick(() => {
        this.$refs.historicalFile.fileDirId = row.id
        this.$refs.historicalFile.initVersion()
      })
    },
    // 刷新还原后的文件名
    refreshFileInfo(data) {
      this.lists && this.lists.forEach(item => {
        if (item.id === data.oldId) {
          item.id = data.newId
          item.name = data.newName
          this.$forceUpdate()
        }
      })
    },
    test() {
      console.log(this.lists)
    },
    // 讨论通知
    discussionNotice(row) {
      this.commentsOpen = true
      this.$nextTick(() => {
        this.$refs.comments.init(row.discussId)
        this.$refs.comments.discussFileId = row.id
      })
    },
    getOfficeSwitch() {
      getSysVarValue('office.changxie.enabled').then(response => {
        this.officeSwitchStatus = (response.data.office_changxie_enabled === 'true')
      })
    },
    // 重新上传 选中文件确定后执行
    okPostUploadHook() {
      this.loading = true
    },
    // 刷新重新上传的文件
    replaceNewFile(data) {
      var fileList = this.lists
      if (data === null || data === undefined) {
        this.msgError(this.$t('没有发现被替换的文件!'))
      } else {
        fileList.forEach((item, index) => {
          if (item.id === data.id) {
            data.directoryId = item.directoryId
            data.businessId = item.businessId
            this.lists.splice(index, 1)
            this.lists.push(data)
          }
        })
      }
      this.loading = false
    },
    // 流程中, 旧文件可能不存在Id的解决方法
    replaceNewFileNotOldId(data) {
      console.log('流程下替换文件!')
      if (data === null || data === undefined) {
        this.msgError(this.$t('没有发现被替换的文件!'))
      } else {
        this.lists && this.lists.forEach((item, index) => {
          if (this.isEmpty(item.id) && item.name === data.originalName && item.directoryId === data.directoryId) {
            // 根据上传的新文件从后台获取该文件的信息. 然后替换列表的文件进行展示
            getFileById(data.id).then(response => {
              this.lists.splice(index, 1)
              if (response.data != null && response.data.length > 0) {
                var tempFile = response.data[0]
                data.id = tempFile.id
                data.name = data.name || data.fileName || data.originalName
                data.createBy = tempFile.createBy
                data.updateBy = tempFile.updateBy
                data.createTime = tempFile.createTime
                data.updateTime = tempFile.updateTime
              }
              this.lists.push(data)
            })
          }
          this.loading = false
        })
      }
    },
    isDisabled(row) {
      // 没有文件时 不能编辑
      if (row.id === '' || row.id === undefined || row.id === null) {
        return true
      }
      // 后缀不为这些时不能编辑
      const availableSuffixes = '.doc.docx.xls.xlsx.ppt.pptx'
      var flag = false
      if (row.name !== null && row.name !== undefined) {
        flag = !availableSuffixes.includes(row.name.substring(row.name.lastIndexOf('.') + 1, row.name.length))
      }
      return flag
    },
    /** 编辑按钮展示 **/
    editBtnShow(scope) {
      var flag = true
      if (!this.isEmpty(scope.row.fileLibraryRole)) {
        flag = ((scope.row.fileLibraryRole.deleteYourself === 'Y' && (scope.row.createBy !== null ? scope.row.createBy.id === this.$store.state.user.userId : false)) || scope.row.fileLibraryRole.deleteAll === 'Y')
      }
      return this.btnShow === true && this.officeSwitchStatus && flag
    },
    /** 下载按钮展示 **/
    downloadBtnShow(scope) {
      var flag = true
      if (!this.isEmpty(scope.row.fileLibraryRole)) {
        flag = ((scope.row.fileLibraryRole.downloadYourself === 'Y' && (scope.row.createBy !== null ? scope.row.createBy.id === this.$store.state.user.userId : false)) || scope.row.fileLibraryRole.downloadAll === 'Y')
      }
      return this.configDownloadEnabled && flag
    },
    /** 删除按钮暂时 **/
    deleteBtnShow(scope) {
      var flag = true
      if (!this.isEmpty(scope.row.fileLibraryRole)) {
        flag = ((scope.row.fileLibraryRole.deleteYourself === 'Y' && (scope.row.createBy !== null ? scope.row.createBy.id === this.$store.state.user.userId : false)) || scope.row.fileLibraryRole.deleteAll === 'Y')
      }
      return this.btnShow && scope.row.dataId && !scope.row.deleteStatus && flag
    },
    /** 版本及讨论按钮显示 **/
    versionBtnShow(scope) {
      var flag = true
      if (!this.isEmpty(scope.row.fileLibraryRole)) {
        flag = scope.row.fileLibraryRole.preview === 'Y'
      }
      return !this.isEmpty(scope.row.id) && flag
    },
    /** 重新上传展示 **/
    reloadBtnShow(scope) {
      var flag = true
      if (!this.isEmpty(scope.row.fileLibraryRole)) {
        flag = scope.row.fileLibraryRole.upload === 'Y'
      }
      return !this.isEmpty(scope.row.name) && flag
    },
    // 新创建的讨论. 因为页面上的 文件还没有id 这里创建完后 把讨论Id赋值给这个文件
    discussionNoticeRefresh(discussId, fileId) {
      if (discussId && fileId) {
        this.lists.forEach(item => {
          if (item.id === fileId) {
            item.discussId = discussId
          }
        })
      }
    },
    getRowKeys(row) {
      return row.id
    },
    autoFileListSort() {
      this.lists.forEach((item, index) => {
        item.fileSort = index + 1
      })
    },
    rowDrop() {
      // 行拖拽
      const _this = this
      const tbody2 = this.$refs.table.$el.querySelector('.el-table__body-wrapper tbody')
      Sortable.create(tbody2, {
        handle: '.handle',
        animation: 500,
        fallbackOnBody: true,
        onChoose() {
          // 选择元素
          _this.lists[_this.lists.length - 1].fixed = false
        },
        onUnchoose: function(evt) {
          // 取消选择元素
          if (evt) {
            _this.lists[_this.lists.length - 1].fixed = 'right'
          }
        },
        onEnd(evt) {
          _this.lists.splice(evt.newIndex, 0, _this.lists.splice(evt.oldIndex, 1)[0])
          var newArray = _this.lists.slice(0)
          _this.lists = []
          _this.$nextTick(() => {
            _this.lists = newArray
            _this.lists.forEach((item, index) => {
              item.fileSort = index + 1
            })
          })
        }
      })
      this.$forceUpdate()
    },
    checkAndSetValue(rule, value, callback) {
      // 校验第几行
      const rowIndex = parseInt(rule.field.substring(rule.field.indexOf('.') + 1, rule.field.lastIndexOf('.')))
      const fieldIndex = parseInt(rule.field.substring(rule.field.indexOf('[') + 1, rule.field.lastIndexOf('[')))
      // 校验的字段名字
      // const ruleName = rule.field.substring(rule.field.lastIndexOf('['), rule.field.length).replaceAll('[', '').replaceAll(']', '')
      // 获取该字段的值
      value = this.lists[rowIndex].slotData[fieldIndex].value
      // if (value) {
      //   if (typeof value === 'object') {
      //     try {
      //       this.lists[rowIndex].slotData[fieldIndex].value = JSON.stringify(value)
      //     } catch (e) {
      //       console.log(e)
      //       this.lists[rowIndex].slotData[fieldIndex].value = value
      //     }
      //   } else {
      //     this.lists[rowIndex].slotData[fieldIndex].value = value
      //   }
      // }
      // // 获取是否需要校验必填
      var checkFlag = true
      // this.slotInputBoxDataArr.some(item => {
      //   if (item.model === ruleName) {
      //     checkFlag = this.isEmpty(item.required) ? false : (item.required === 'true' ? true : item.required)
      //     return true
      //   }
      // })
      // 校验必填状态
      if (this.isEmpty(value) && checkFlag) {
        callback(new Error(this.$t('必填信息')))
      } else {
        callback()
      }
    },
    // 插槽change事件
    changeSelect(e, index, model, row) {
      this.$emit('changeSlotSelect', { e, index, model, row })
      this.$forceUpdate()
    },
    // 插槽数字事件
    changeSlotNumber(e, index, model, row) {
      this.$emit('changeSlotNumber', { e, index, model, row })
      this.$forceUpdate()
    },
    // 插槽文本时间
    changeSlotInput(e, index, model, row) {
      this.$emit('changeSlotInput', { e, index, model, row })
      this.$forceUpdate()
    }
  }
}
</script>
<style type="text/scss" lang="scss" scoped>
.directory-handle{
  text-align: left;
  display: flex;
  align-items: center;
  column-gap: 5px;
  span{
    flex: 1;
    overflow: hidden;
    text-overflow: ellipsis;
    line-height: 16px;
    font-weight: 700;
  }
  .isDirectory{
    position: relative;
    &::before{
      content: '*';
      color: #ff4949;
      margin-right: 4px;
    }
  }
}

.handle, .canDrag {
  cursor: move;
  user-select:none;
}

::v-deep .hover-row > td {
  background-color: #fff !important;
}

::v-deep .sortable-chosen > td {
  // 拖动的样式
  background-color: #eff2f6 !important;
}

::v-deep .el-table--enable-row-hover .el-table__body tr:hover > td {
  // 修复拖拽的时候hover的不消失的问题
  background-color: #fff;
}
/deep/.upload-single{
  border-radius: 3px;
  color: #fff;
  display: inline-block;
  white-space: nowrap;
  cursor: pointer;
  font-weight: 500;
  font-size: 12px;
  border: 1px solid rgba(82, 88, 224, 0.2) !important;
  background-color: transparent !important;
  font-family: PingFang SC;
  line-height: 1;
  font-weight: 400;
  .uploader-btn{
    color: #fff;
    border: unset;
  }
}
</style>
